package com.springboot.apiexample.annotation;

import com.google.common.cache.Cache;
import com.springboot.apiexample.common.StringUtils;
import com.springboot.apiexample.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 接口幂等性 拦截器
 *
 * @author NiJo_H
 * @version 1.0
 */
@Slf4j
public class ApiIdempotentInterceptor implements HandlerInterceptor {
    @Autowired
    private Cache<String,Object> cacheApi;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        ApiIdempotent methodAnnotation = method.getAnnotation(ApiIdempotent.class);
        if (methodAnnotation != null) {
            //幂等性校验
            check(request);
        }

        return true;
    }

    private void check(HttpServletRequest request) {
        //获取请求UID
        String formId = request.getParameter("formId");
        if (StringUtils.isNotEmpty(formId) && Objects.nonNull(cacheApi.getIfPresent(formId))) {
            log.info("删除key=" + formId + ";状态:成功");
        } else {
            throw new BusinessException("无效表单id,请重新刷新页面");
        }

    }


}
